package com.rslai.commons.ssh;

import com.jcraft.jsch.JSchException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeoutException;

public abstract class AbstractSSH {
    private final Log log = LogFactory.getLog(getClass());

    protected SSHConfig sshConfig; // ssh配置信息

    protected boolean isConnect = true; // 是否是connect，true：当是JumpServer 读最后是 "> " 认为结束，否则读最后是 "# " 或 "$ " 认为结束

    /**
     * 构造函数
     * @param sshConfig ssh配置信息
     */
    public AbstractSSH(SSHConfig sshConfig) {
        this.sshConfig = sshConfig;
        isConnect = true;
    }

    /**
     * 执行一条命令
     * @param command 命令内容，不能包含\r\n
     * @return 返回执行的结果
     * @throws IOException
     * @throws JSchException
     * @throws TimeoutException
     */
    public SSHResponse execute(String command) throws IOException, JSchException, TimeoutException {
        isConnect = false;
        return null;
    }

    /**
     * 打印日志，打印收到的信息
     * @param logInfo
     */
    protected void sshInLog(String logInfo) {
        sshLog("<== ", logInfo);
    }

    /**
     * 打印日志，打印发出的信息
     * @param logInfo
     */
    protected void sshOutLog(String logInfo) {
        sshLog("--> ", logInfo);
    }

    /**
     * 打印日志
     * 按行读 logInfo ，每一行 log 一次
     * @param rr
     * @param logInfo
     */
    private void sshLog(String rr, String logInfo) {
        if (log.isDebugEnabled()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(logInfo.getBytes())));
            try {
                String str = null;
                while ((str = br.readLine()) != null) {
                    log.debug(rr + str);
                }
            } catch (IOException e) {
            } finally {
                try {
                    if (br != null) br.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @Override
    public String toString() {
        return "SSH{" +
                "sshConfig=" + sshConfig +
                ", isConnect=" + isConnect +
                '}';
    }
}
